<?php
// questo script aggiunge nella tabella manufacturer_to_store
// le marche inserite non presenti
 
// Configuration
require_once('../config.php');

$file_log = '';

if ( count($argv) ) {
	$file_log = $argv[1];
}

define ('FILE_LOG',   $file_log);

// Startup
require_once(DIR_SYSTEM . 'startup.php');

// Config
$config = new Config();

// Database
$db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);

require_once('common.php');

function getCategoryId( $category_code ) {

  global $db;
  
  $queryStr = "select category_id from category_description  
                where category_code = '$category_code'";
  
  $query = $db->query($queryStr);
  
  if ( $query->num_rows ) {
    return $query->row['category_id'];
  }
  
  return -1;
}


$queryStr = "select * from category_to_category_load where elab_chk = 0";

$category_load = $db->query($queryStr);

if ($category_load->num_rows) {
	
  LogBatch::getInstance()->write('Ci sono categorie '. $category_load->num_rows .' caricate sulla category_to_category_load');

	foreach ($category_load->rows as $category) {
	
	  $category_id = -1;
	  $category_parent_id = null;
	  
    $category_code  = trim($category['category_code']);
    $category_code_parent  = trim($category['category_code_parent']);    

    $queryStr = "select category_id from category_description cd where cd.category_code = '$category_code'";
    $query = $db->query($queryStr);

    $category_id = getCategoryId( $category_code );
    if ( $category_code_parent != '' )
      $category_parent_id = getCategoryId( $category_code_parent );
    
    
    if ( $category_id != -1 ){
      
      $top = 1;
      if ( $category_parent_id != null && $category_parent_id != -1 ) {
        $top = 0;
        $category_parent_id = (int) $category_parent_id;
      } else {
        $category_parent_id = 'null';
      }
      
      $queryStr = "update category
                    set top = $top, 
                        parent_id = $category_parent_id
                    where category_id = $category_id";
      $db->query($queryStr);      
    }
    
	}

  LogBatch::getInstance()->write('Aggiorno tutti i record sulla category_to_category_load ');

  $db->query("update category_to_category_load set elab_chk = 1 where elab_chk = 0");
	
} else {
  LogBatch::getInstance()->write('Non ci sono categorie caricate sulla category_to_category_load');
}

